package jjn.round1;

/**
 * @author Jjn
 * @since 2022/10/23 18:46
 */
public class LeetCode5_LongestPalindromicSubstring {
    public String longestPalindrome(String s) {
        String max = "";
        for (int i = 0; i < s.length(); i++) {
            String substring = maxSubstringWithIndex(i, s);
            if (substring.length() > max.length()) {
                max = substring;
            }
        }
        return max;
    }

    private String maxSubstringWithIndex(int index, String s) {
        int left = index - 1, right = index + 1;
        while (left > 0 && s.charAt(left) == s.charAt(index)) {
            left--;
        }
        while (right < s.length() && s.charAt(right) == s.charAt(index)) {
            right++;
        }
        while (left >= 0 && right < s.length()) {
            if (s.charAt(left) == s.charAt(right)) {
                left--;
                right++;
            } else {
                break;
            }
        }
        left = Math.max(0, ++left);
        right = Math.min(right, s.length());
        return s.substring(left, right);
    }
}
